# import random
import time
import requests
import redis
from time import sleep
import threading
from work.commom.OperateMysql import OperateMysql


class Request:
    @staticmethod
    def post(url, json=None, params=None, headers=None):
        try:
            res = requests.post(url=url, json=json)
            return res
        except Exception as e:
            print(e)


def redis_count(func):
    """
    查看redis条数的装饰器
    :param func:方法名
    :return:wrapper
    """

    def wrapper(*args, **kwargs):
        r = redis.Redis(host='10.0.17.17', port=6379, decode_responses=True)
        start = r.dbsize()
        f = func(*args, **kwargs)
        sleep(5)
        end = r.dbsize()
        if start < end:
            print(f'共增加了{end - start}条redis记录')
        elif start > end:
            print(f'共减少了{start - end}条redis记录')
        return f

    return wrapper


def post(url=None, data=None, times=100):
    """
    实现post批量请求
    :param url: url
    :param data: data
    :param times: 循环次数
    :return: None
    """
    succ_count = 0
    for _ in range(times):
        res = requests.post(url=url, json=data)
        if res.json()['code'] == "20000" and res.status_code == 200:
            succ_count += 1
        else:
            continue
    print(f'总共执行了{times}次接口操作,成功了{succ_count}次')


@redis_count
def multi_thread(threads_num, url, data, times):
    """
    实现多线程运行
    :param threads_num:线程数
    :param url:
    :param data:
    :param times:每个线程中的循环次数
    :return:None
    """
    threads = []
    for _ in range(threads_num):
        threads.append(threading.Thread(target=post, args=(url, data, times)))

    for thread in threads:
        thread.start()

    for thread in threads:
        thread.join()


def total_redis(name=None, tablename=None, database=None):
    """
    查看redis数据总量或根据name匹配查询某个目录下redis总数
    :param database: 数据库名称
    :param tablename: 表名
    :param name: 匹配的redis中的name
    :return:
    """
    sql = f"""select count(1) from {tablename}"""
    mysql = OperateMysql(database=database)
    count = mysql.excute_sql(sql)[0][0]
    r = redis.Redis(host='10.0.17.17', port=6379, decode_responses=True)
    start = len(r.keys(pattern=name)) if name else r.dbsize()
    time1 = time.time()
    while True:
        sleep(1)
        end = len(r.keys(pattern=name)) if name else r.dbsize()
        time2 = time.time()
        if start < end:
            print(f'共增加了{end - start}条redis记录,耗时{round((time2 - time1), 2)}秒')
        elif start > end:
            print(f'共减少了{start - end}条redis记录,耗时{round((time2 - time1), 2)}秒')
        elif time2 - time1 > 300 or abs(start - end) == count:
            print('结束了，再见')
            break
        else:
            print('啥事没有')

# 新增设备
# if __name__ == '__main__':
#     url = 'http://10.0.17.17:8806/client/addClient/v1'
#     data = {"parentClientId": "", "rootClientId": "", "extTypeCode": "jinsd",
#             "extData": {"client_name": "test1", "client_code": 11111, "power": "1"}}
# for i in range(100):
#     multi_thread(100, url=url, data=data, times=1)
# sleep(15)
# for i in range(10000):
#     post(url, data)
#     data['extData']['client_code']+= 1
# 新增单元
# if __name__ == '__main__':
#     url = 'http://10.0.17.17:8803/unit/addUnit/v1'
#     data = {"unitId": "", "rootUnitId": "4206592", "parentUnitId": "4206592", "extTypeCode": "ceshi",
#             "extData": {"unit_name": "test_jins", "wind": 123, "power": "test456"}}
#     multi_thread(10, url=url, data=data, times=50)
# total_redis(tablename='unit_testabc', database='unit_center')
#
# r = redis.Redis(host='10.0.17.17', port=6379, decode_responses=True)
# print(len(r.keys(pattern='UNIT_CENTER:*')))
#
# print(2)
# for i in r.keys(pattern='UNIT_CENTER:testabc*'):
#     r.hdel(i, 'state')
# print(r.dbsize())
